package com.bbeginner.learn.no4.sql;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bbeginner.learn.R;
import com.bbeginner.learn.no2.practice.LoginForgetActivity;
import com.bbeginner.learn.no4.bean.UserInfo;
import com.bbeginner.learn.no4.database.UserDBHelper;
import com.bbeginner.learn.util.DateUtil;
import com.bbeginner.learn.util.ViewUtil;

public class LoginSQLiteActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

    private RadioGroup rg_login;
    private RadioButton rb_password;
    private RadioButton rb_verifycode;
    private EditText et_phone;
    private TextView tv_password;
    private EditText et_password;
    private Button btn_forget;
    private CheckBox ck_remember;
    private Button btn_login;

    private int mRequestCode = 0;
    private int mType = 0;
    private boolean bRemember = false;
    private String mPassword = "111111";
    private String mVerifyCode;
    private UserDBHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_sqlite);

        initView();
    }

    private void initView() {
        rg_login = (RadioGroup) findViewById(R.id.rg_login);
        rb_password = (RadioButton) findViewById(R.id.rb_password);
        rb_verifycode = (RadioButton) findViewById(R.id.rb_verifycode);
        et_phone = (EditText) findViewById(R.id.et_phone);
        tv_password = (TextView) findViewById(R.id.tv_password);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_forget = (Button) findViewById(R.id.btn_forget);
        ck_remember = (CheckBox) findViewById(R.id.ck_remember);
        btn_login = (Button) findViewById(R.id.btn_login);

        /**
         * new 后面的全部创建一遍
         * RadioListener
         * CheckListener
         * HideTextWatcher
         * typeArray
         * TypeSelectedListener
         */
        rg_login.setOnCheckedChangeListener(new RadioListener());
        ck_remember.setOnCheckedChangeListener(new CheckListener());
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone));
        et_password.addTextChangedListener(new HideTextWatcher(et_password));
        btn_forget.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        et_password.setOnFocusChangeListener(this);

        /**
         * 下拉列表的数据加载
         * 监听下拉列表选择了什么
         *
         * 详细见No1的行星模块
         */
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
                R.layout.item_select, typeArray);
        typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
        Spinner sp_type = (Spinner) findViewById(R.id.sp_type);
        sp_type.setPrompt("请选择用户类型");
        sp_type.setAdapter(typeAdapter);
        sp_type.setSelection(mType);
        sp_type.setOnItemSelectedListener(new TypeSelectedListener());
    }

    /**
     * 写在上头的里面没问题
     * 因为下面也用到,所以写出来
     */
    private String[] typeArray = {"个人用户", "公司用户"};

    /**
     * 点击密码,验证码
     * 展示两种不同的布局
     */
    private class RadioListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_password) {
                tv_password.setText("登录密码：");
                et_password.setHint("请输入密码");
                btn_forget.setText("忘记密码");
                ck_remember.setVisibility(View.VISIBLE);
            } else if (checkedId == R.id.rb_verifycode) {
                tv_password.setText("　验证码：");
                et_password.setHint("请输入验证码");
                btn_forget.setText("获取验证码");
                ck_remember.setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 是否勾选记住密码
     */
    private class CheckListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == R.id.ck_remember) {
                bRemember = isChecked;
            }
        }
    }

    /**
     * 限定输入字符的最大长度
     */
    private class HideTextWatcher implements TextWatcher {
        private EditText mView;
        private int mMaxLength;
        private CharSequence mStr;

        /**
         * Utils
         *
         * EditText 的值命名为 v
         * 把 v 的值赋值给 mView
         * @param v
         */
        public HideTextWatcher(EditText v) {
            super();
            mView = v;
            mMaxLength = ViewUtil.getMaxLength(v);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mStr = s;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (mStr == null || mStr.length() == 0)
                return;
            if ((mStr.length() == 11 && mMaxLength == 11) ||
                    (mStr.length() == 6 && mMaxLength == 6)) {
                ViewUtil.hideOneInputMethod(LoginSQLiteActivity.this, mView);
            }
        }
    }

    /**
     * parent, View view, int position, long id
     * (AdapterView<?> parent)
     *
     * 在 initView 中赋值的 mType
     */
    private class TypeSelectedListener implements android.widget.AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            mType = arg2;
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }

    /**
     * et_phone.getText().toString()
     * 获取文字 转化为字符
     * @param v
     */
    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        /**
         * 监听 forget 按钮
         * 密码 跳转页面,并传送数据到 onActivityResult
         * 验证码 显示AlertDialog,获得验证码
         *
         * 监听 login 按钮
         */
        if (v.getId() == R.id.btn_forget) {
            if (phone==null || phone.length()<11) {
                Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                return;
            }
            /**
             * 点击 forget 按钮 如果此时选中的是密码登录
             * mRequestCode 在 onActivityResult
             */
            if (rb_password.isChecked() == true) {
                Intent intent = new Intent(this, LoginForgetActivity.class);
                intent.putExtra("phone", phone);
                startActivityForResult(intent, mRequestCode);
                /**
                 * 点击 forget 按钮 如果此时选中的是验证码登录
                 * 验证码用 Math.random 随机生成
                 * 展示使用 AlertDialog
                 *
                 * 通过 AlertDialog.Builder 设置完参数，
                 * 还需调用 create 方法才能生成 AlertDialog 对象。
                 * 最后调用 AlertDialog 对象的 show 方法，在页面上弹出提醒对话框。
                 */
            } else if (rb_verifycode.isChecked() == true) {
                mVerifyCode = String.format("%06d", (int)(Math.random()*1000000%1000000));
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请记住验证码");
                builder.setMessage("手机号"+phone+"，本次验证码是"+mVerifyCode+"，请输入验证码");
                builder.setPositiveButton("好的", null);
                AlertDialog alert = builder.create();
                alert.show();
            }
        /**
         * phone==null || phone.length()<11
         * 判断号码长度是否正确,因为有11位的输入限制,所以号码位数不会超过11位
         * getText().toString().equals
         * 判断密码是否正确
         *
         * 调用 loginSuccess 方法
         */
        } else if (v.getId() == R.id.btn_login) {
            if (phone==null || phone.length()<11) {
                Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                return;
            }
            if (rb_password.isChecked() == true) {
                if (et_password.getText().toString().equals(mPassword) != true) {
                    Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    loginSuccess();
                }
            } else if (rb_verifycode.isChecked() == true) {
                if (et_password.getText().toString().equals(mVerifyCode) != true) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    loginSuccess();
                }
            }
        }
    }

    /**
     * 获取更改后的密码
     *
     * 自动清空的操作放在 onActivityResult 方法中处理是一个办法，
     * 但这样处理有一个问题，如果用户直接按返回键回 到登录页面，
     * onActivityResult 方法发现数据为空就不会处理
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == mRequestCode && data != null) {
            //用户密码已改为新密码
            mPassword = data.getStringExtra("new_password");
        }
    }

    /**
     * 清空密码框的处理
     * 从修改密码页面返回登录页面，要清空密码的输入框
     */
    @Override
    protected void onRestart() {
        et_password.setText("");
        super.onRestart();
    }

    /**
     * 1.声明一个 UserDBHelper 对象，
     * 然后在活动页面的 onResume 方法中打开数据库连接，
     * 在 onPasue 方法中关闭数据库连接
     *
     * UserDBHelper getInstance
     * mHelper.openWriteLink
     * mHelper.closeLink
     */
    @Override
    protected void onResume() {
        super.onResume();
        mHelper = UserDBHelper.getInstance(this, 2);
        mHelper.openWriteLink();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mHelper.closeLink();
    }
    /**
     * 展示登录成功界面
     * 记住密码的话插入数据到数据库中
     */
    private void loginSuccess() {
        /**
         * mType 判断为哪一类用户
         * %s,输出后面的变量值
         */
        String desc = String.format("您的手机号码是%s，类型是%s。恭喜你通过登录验证，点击“确定”按钮返回上个页面",
                et_phone.getText().toString(), typeArray[mType]);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确定返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("我再看看", null);
        AlertDialog alert = builder.create();
        alert.show();

        /**
         * user info bean
         * data utils
         * mHelper.insert
         */
        if (bRemember) {
            UserInfo info = new UserInfo();
            info.phone = et_phone.getText().toString();
            info.password = et_password.getText().toString();
            info.update_time = DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss");
            mHelper.insert(info);
        }
    }


    /**
     * 为什么光标进入密码框事件不选onClick？因为要点两下才会触发onClick动作（第一下是切换焦点动作）
     * 使用焦点变更器,将数据库查询操作放在该方法中，
     *用户输入手机号后光标还停留在手机框，
     * 接着点击密码框，光标随之跳到密码框，这时密码框自动填入了该手机号对应的密码串
     */

    /**
     * mHelper.queryByPhone
     *
     * 获取正在输入的手机号,转化为字符串
     * 如果 id 变为密码懒
     * 判断手机号是否>0,焦点是否在密码栏
     * 因为之前的登录存储的数据必定是11位,所以这里只需判断输入数据即可
     *
     * 调用 queryByPhone从数据库中查找对应的手机号
     * 如果手机号不为空,则自动填入密码
     *
     * @param v
     * @param hasFocus
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        String phone = et_phone.getText().toString();
        if (v.getId() == R.id.et_password) {
            if (phone.length() > 0 && hasFocus == true) {
                UserInfo info = mHelper.queryByPhone(phone);
                if (info != null) {
                    et_password.setText(info.password);
                }
            }
        }
    }
}